package com.bins.knowledge.point.algorithm;

public class LinkedListCycle {

    // 链表节点定义
    public static class ListNode {
        int value;
        ListNode next;
        ListNode(int x) {
            value = x;
            next = null;
        }
    }

    public static boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        ListNode slow = head;
        ListNode fast = head.next;
        
        while (fast != null && fast.next != null) {
            if (slow == fast) {
                return true;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        
        return false;
    }
    

    
    public static void main(String[] args) {
        // 测试用例1：有环
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node2; // 形成环
        
        System.out.println(hasCycle(node1)); // 输出: true
        
        // 测试用例2：无环
        ListNode node5 = new ListNode(1);
        ListNode node6 = new ListNode(2);
        ListNode node7 = new ListNode(3);
        node5.next = node6;
        node6.next = node7;
        node7.next = null;
        
        System.out.println(hasCycle(node5)); // 输出: false
    }
}